#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <cerrno>
#include <unistd.h>
#include <iostream>
#include <fcntl.h>

#define Defaultfd -1
#define Creater 1
#define User 2
#define SIZE 128
#define Read O_RDONLY
#define Write O_WRONLY

const std::string path = "./myfifo";
class NamedPipe
{
private:
    bool OpenNamePipe(int mode)
    {
        _fd = open(_fifo_path.c_str(), mode);
        if (_fd < 0)
            return false;
        return true;
    }

public:
    NamedPipe(const std::string path, int who)
        : _fifo_path(path), _id(who), _fd(Defaultfd)
    {
        if (_id == Creater)
        {
            int ret = mkfifo(_fifo_path.c_str(), 0666);
            if (ret != 0)
            {
                std::perror("mkfifo");
            }
            std::cout << "Creater creat namedpipe!" << std::endl;
        }
    }
    bool OpenforRead()
    {
        return OpenNamePipe(Read);
    }

    bool OpenforWrite()
    {
        return OpenNamePipe(Write);
    }

    int ReadNamedPipe(std::string *out)
    {
            char buffer[SIZE];
            int n = read(_fd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = '\0';
                *out = buffer;
            }
            return n;
    }
    int WriteNamedPipe(std::string& in)
    {
       return write(_fd,in.c_str(),in.size());
    }
    ~NamedPipe()
    {
        if (_id == Creater)
        {
            int ret = unlink(_fifo_path.c_str());
            if (ret != 0)
            {
                std::perror("unlink");
            }
            std::cout << "Creater free namedpipe!" << std::endl;
        }
    }
private:
    std::string _fifo_path;
    int _id;
    int _fd;
};